//
//  YZAutoJumpCell.m
//  VET
//
//  Created by Lam BG on 2018/7/13.
//  Copyright © 2018年 YZ. All rights reserved.
//

#import "YZAutoJumpCell.h"

#import "YZPigModel.h"
#import "YZWorkNoteModel.h"
#import "YZSwineryModel.h"
#import "YZAutoRowModel.h"
#import "YZAutoItemModel.h"

// auto cell id enum
#import "YZAutoFormHeader.h"
#import "YZStatementHeader.h"

#import "YZRouter.h"
#import "YZAutoCache.h"
#import "YZJsonFileLoader.h"
#import "YZAutoCellFactory.h"

// view
#import "PopoverView.h"
#import "YZActionSheet.h"
#import "YZDatePickView.h"
#import "YZArchieveOptionVC.h"
#import "YZSwineOptionPickerView.h"

// 第三方
#import "TBCityIconFont.h"

// categoru
#import "YZRouter+AutoVC.h"
#import "UIImage+Category.h"
#import "NSString+Category.h"
#import "UIResponder+Router.h"
#import "NSDate+YZDatePickView.h"

@interface YZAutoJumpCell () <YZActionSheetDelegate>

@property (weak, nonatomic) IBOutlet UILabel *formTitle;

@property (weak, nonatomic) IBOutlet UILabel *tipsLabel;

@property (weak, nonatomic) IBOutlet UILabel *valueLabel;

@property (weak, nonatomic) IBOutlet UIImageView *arrorImg;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *arrorConstant;

@property (weak, nonatomic) IBOutlet UIButton *selectBtn;

@property (nonatomic, strong) NSArray *items;

@end

@implementation YZAutoJumpCell

#pragma mark -

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    
    self.arrorImg.image = [UIImage iconWithInfo:TBCityIconInfoMake(@"\ue63c", 16, kColorWithHex(0x9B9B9B))];
    [self.selectBtn setBackgroundImage:[UIImage imageWithColor:kColorWithHex(0x2FC66A)] forState:UIControlStateHighlighted];
}

#pragma mark -

- (void)setupCellView {
    [super setupCellView];
    
    // 有默认值的 cell
    [[YZAutoCellFactory sharedInstance] sutupRowModelDefaultValue:self.rowModel];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        self.formTitle.attributedText = [self.rowModel attributedTitle];
        self.valueLabel.text = self.rowModel.displayValue;
        self.tipsLabel.text  = self.rowModel.tips;
        
        // 箭头（详情时隐藏）
        BOOL hideArror = self.rowModel.isUnEdit;
        self.arrorImg.hidden = hideArror;
        if (hideArror) {
            
            self.arrorConstant.constant = 16;
        }
    });
}

#pragma mark - event action

- (IBAction)selectClicked:(id)sender {
    
    // 先取消掉输入的事件
    UITableView *next = (UITableView*)self.nextResponder;
    [next endEditing:YES];
    
    // 根据 action 跳转
    AutoCellType cellType = ((YZAutoRowModel*)self.rowModel).type;
    if (cellType == AutoCellTypeActionSheet) {
        
        [self popActionSheet];
    }
    
    if (cellType == AutoCellTypeSelectSheet) {
        
        [self popSelectSheet];
    }
    
    if (cellType == AutoCellTypeJumpVC) {
        
        [self popTargetVC];
    }
    
    if (cellType == AutoCellTypeSelectPigVC ||
        cellType == AutoCellTypeSelectPigsVC) {
        
        [self popSelectPigVC];
    }
    
    if (cellType == AutoCellTypeJumpTime) {
        
        [self popTimePicker];
    }
}

/* sheet 设置 value */
- (void)setItemValue:(YZAutoItemModel *)item {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        self.rowModel.paramValue = [@(item.itemKey) stringValue]; // 设置上传值
        self.valueLabel.text = self.rowModel.displayValue = item.itemValue; // 设置显示值
    });
  
    // 特殊需要传递处理的
    if (item) {
        
        [self routeEvent:@"" userInfo:@{@"item" : item}];
    }
}

#pragma mark - 弹出逻辑

- (void)popSelectSheet {
    
    // 加载 sheet 数据
    NSString *action = ((YZAutoRowModel*)self.rowModel).action;
    NSAssert(action.length != 0, @"数据出错 请检查");
    
    [[[YZAutoCache sharedInstance] getAutoCellItems:action] subscribeNext:^(NSArray *items) {
        
        // 如果有默认选中直接显示，没有就选中第一项
        NSString *defalultValue = ((YZAutoRowModel*)self.rowModel).paramValue;
        if (defalultValue.length == 0) {
            
            YZAutoItemModel *item = items[0];
            defalultValue = [@(item.itemKey) stringValue];
        }
        
        [YZSwineOptionPickerView showStringPickerWithTitle:self.rowModel.title
                                                dataSource:items
                                           defaultSelValue:defalultValue
                                              isAutoSelect:NO
                                                themeColor:nil
                                               resultBlock:^(id item) {
                                                   
                                                   // 填充数据
                                                   [self setItemValue:item];
                                               }];
        
    } error:^(NSError * _Nullable error) {
        
    }];
}

- (void)popActionSheet {
    
    // 加载 sheet 数据
    NSString *action = ((YZAutoRowModel*)self.rowModel).action;
    NSAssert(action.length != 0, @"数据出错 请检查");
    
    [[[YZAutoCache sharedInstance] getAutoCellItems:action] subscribeNext:^(NSArray *items) {
        
        self.items = items;
        NSMutableArray *titles = [NSMutableArray array];
        for (YZAutoItemModel *item in items) {
            
            [titles addObject:item.itemValue];
        }
        YZActionSheet *sheet = [[YZActionSheet alloc] initWithTitle:nil sheetTitles:titles cancleBtnTitle:@"取消" sheetStyle:YZActionSheetDefault delegate:self];
        sheet.sheetHeight = 54;
        [sheet show];
        
    } error:^(NSError * _Nullable error) {
        
    }];
}

- (void)actionSheet:(YZActionSheet *)actionSheet clickButtonAtIndex:(NSInteger)buttonIndex {
    
    if (self.items) {
        
        YZAutoItemModel *item = self.items[buttonIndex];
        // 填充数据
        [self setItemValue:item];
    }
}

- (void)actionSheetCancle:(YZActionSheet *)actionSheet {}

- (void)popTargetVC {
    
    NSString *action = ((YZAutoRowModel*)self.rowModel).action;
    
    NSAssert(action.length > 0, @"数据出错 请检查");
    
    [[YZRouter sharedInstance] yz_atuoPush:action params:@{@"rowModel" : self.rowModel}];
}

- (void)popTimePicker {
    
    // 最小时间
    NSDate *minDate = [[YZAutoCellFactory sharedInstance] popMinDate:self.rowModel];
    // 传入控件的日期格式
    NSString *defaultSelValue = [NSDate yz_getDateString:[NSDate dateWithTimeIntervalSince1970:[self.rowModel.paramValue integerValue]] format:[[YZAutoCellFactory sharedInstance] showPickViewDateFormat:self.rowModel]];
    
    // 弹出
    [YZDatePickView showDatePickerWithTitle:self.rowModel.title
                                   dateType:[[YZAutoCellFactory sharedInstance] showPickViewDatePickerMode:self.rowModel]
                            defaultSelValue:defaultSelValue
                                    minDate:minDate
                                    maxDate:nil
                               isAutoSelect:NO
                                 themeColor:[UIColor blackColor]
                                resultBlock:^(NSString *selectValue) {
                                    
                                    dispatch_async(dispatch_get_main_queue(), ^{
                                        
                                        NSTimeInterval timeInterval = [NSDate yz_getDateTimeInterval:selectValue format:[[YZAutoCellFactory sharedInstance] showPickViewDateFormat:self.rowModel]];
                                        self.rowModel.paramValue = [@(timeInterval) stringValue]; // 设置上传值
                                        self.valueLabel.text = self.rowModel.displayValue = [NSDate yz_getDateStringFromTimeInterval:timeInterval format:[[YZAutoCellFactory sharedInstance] showDateFormat:self.rowModel]]; // 设置显示值
                                    });;
                                }];
}

- (void)popSelectPigVC {
    
    NSArray *selected = nil;
    NSMutableArray *selectArray = [NSMutableArray array];
    YZArchieveOptionType optionType = 0;
    AutoCellType cellType = ((YZAutoRowModel*)self.rowModel).type;
    
    if (self.rowModel.paramValue.length) {
        
        // 获取选中
        selected = [self.rowModel.paramValue componentsSeparatedByString:@","];
    }
    
    // 猪只 猪群 
    if (cellType == AutoCellTypeSelectPigVC) optionType = YZArchieveOptionPig;
    if (cellType == AutoCellTypeSelectPigsVC) optionType = YZArchieveSingleSwinery;
    
    // 已选择状态
    for (NSString *ids in selected) {
        
        NSArray *idsArray = [ids componentsSeparatedByString:@"+"];
        NSString *idString = idsArray[0];
        YZArchiveModel *selectModel = [[YZArchiveModel alloc] init];
        selectModel.archiveId = [idString integerValue];
        [selectArray addObject:selectModel];
    }
    
    // 猪只 / 猪群 多选
    YZArchieveOptionVC *optionVC = [[YZArchieveOptionVC alloc] initWithOptionType:optionType];
    optionVC.selectedModels = selectArray;
    
    @weakify(self)
    optionVC.archieveSuccessBlock = ^(NSArray *selectedArr) {
        
        @strongify(self)
        NSUInteger count = selectedArr.count;
        if (count > 0) {
            
            NSMutableString *values = [NSMutableString string];
            if (cellType == AutoCellTypeSelectPigVC) {
                
                // 猪只 YZPigModel
                for (YZArchiveModel *pig in selectedArr) {
                    
                    [values appendFormat:@"%ld+%ld,", (long)pig.archiveId, pig.status.itemKey];
                }
                
            } else if (cellType == AutoCellTypeSelectPigsVC) {
                
                // 猪群 YZSwineryModel
                if (selectedArr.count >= 1) {
                    
                    YZArchiveModel *selectSwinery = selectedArr[0];
                    // 拼接 猪只 id + 猪只状态
                    [values appendFormat:@"%ld+%ld,", (long)selectSwinery.archiveId, selectSwinery.status.itemKey];
                    // 选中后设置最大值
                    NSString *result = [values substringToIndex:values.length - 1];
                    [self routeEvent:@"" userInfo:@{@"realQty" : @(selectSwinery.realQty), @"result" : result}];
                }
            }
            
            // 填充数据
            dispatch_async(dispatch_get_main_queue(), ^{
                
                // 删除最后的 ，
                NSString *result = [values substringToIndex:values.length - 1];
                // 设置上传值
                self.rowModel.paramValue = result;
                // 设置显示值
                self.valueLabel.text = self.rowModel.displayValue = [NSString stringWithFormat:@"%ld个对象", count];
            });
        } else {
            
            // 填充数据
            dispatch_async(dispatch_get_main_queue(), ^{

                // 设置上传值
                self.rowModel.paramValue = @"";
                // 设置显示值
                self.valueLabel.text = self.rowModel.displayValue = @"";
            });
        }
    };
    
    [[[YZRouter sharedInstance] currentViewController].navigationController pushViewController:optionVC animated:YES];
}

@end



















